<template>
  <!-- 广告位数据 -->
  <div class="advertising-data">
    <a-form :form="form" :label-col="{ span: 4 }" :wrapper-col="{ span: 12 }">
      <a-row justify="space-between">
        <a-col :span="6" :xxl="6" :xl="12" :lg="12">
          <a-form-item label="名称" :wrapperCol="{ span: 18, offset: 1 }">
            <a-input v-decorator="['name', { initialValue: '' }]" placeholder="请输入" />
          </a-form-item>
        </a-col>
        <a-col :span="6" :xxl="6" :xl="12" :lg="12">
          <a-form-item label="类型" :wrapperCol="{ span: 18, offset: 1 }">
            <a-select v-decorator="['advertisingType', { initialValue: '0' }]">
              <a-select-option value="0">
                互动广告位
              </a-select-option>
              <a-select-option value="2">
                展示广告位
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="12" :xxl="12" :xl="24" :lg="24">
          <div style="dispaly: flex;">
            <span style="margin-right:1rem;">时间区间: </span>
            <a-date-picker :inputReadOnly="true" :allowClear="false" v-model="startTime" show-time />
            -
            <a-date-picker :inputReadOnly="true" :allowClear="false" v-model="endTime" show-time />
          </div>
        </a-col>
        <a-col :span="24" class="right">
          <a-form-item>
            <a-space>
              <a-button @click="resetForm">
                重置
              </a-button>
              <a-button :loading="isLoading" key="submit" type="primary" @click="handleQuery">
                查询
              </a-button>
            </a-space>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <a-row justify="space-between">
      <a-col :span="21">
        <h3>详情列表</h3>
      </a-col>
      <a-col class="right">
        <a-button type="primary" @click="handleExportTable">
          导出
        </a-button>
      </a-col>
    </a-row>
    <a-table
      class="my-table"
      :rowKey="(record) => record.slotId"
      :loading="isLoading"
      @expand="expand"
      :pagination="false"
      :columns="columns"
      :data-source="data"
    >
      <a-table
        :loading="innerIsLoading"
        slot="expandedRowRender"
        slot-scope="record"
        :columns="innerColumns"
        :rowKey="(record) => String(record.slotId)"
        :data-source="record.innerData"
        :pagination="false"
      >
        <span slot="advertClickRate" slot-scope="_, record">
          <span>{{ record.advertShowPv == 0 ? 0 : ((record.advertValidClick / record.advertShowPv) * 100).toFixed(2) }}%</span>
        </span>
        <span slot="customUv" slot-scope="_, record">
          <span>{{
            record.activityShowUv ? (record.activityShowUv == 0 ? '-' : (record.activityJoinPv / record.activityShowUv).toFixed(2)) : '-'
          }}</span>
        </span>
        <span slot="expectIncome" slot-scope="_, record">
          <span>{{ record.expectIncome == 0 ? 0 : (record.expectIncome / 10000).toFixed(2) }}</span>
        </span>
      </a-table>
      <span slot="customUv" slot-scope="_, record">
        <span>{{
          record.activityShowUv ? (record.activityShowUv == 0 ? '-' : (record.activityJoinPv / record.activityShowUv).toFixed(2)) : '-'
        }}</span>
      </span>
      <span slot="customClick" slot-scope="_, record">
        <span>{{ record.advertShowPv == 0 ? 0 : ((record.advertValidClick / record.advertShowPv) * 100).toFixed(2) }}%</span>
      </span>
      <span slot="expectIncome" slot-scope="_, record">
        <span>{{ record.expectIncome == 0 ? 0 : (record.expectIncome / 10000).toFixed(2) }}</span>
      </span>
    </a-table>

    <a-row class="pagination">
      <a-pagination
        show-size-changer
        :default-current="pageNo"
        :total="total"
        :show-total="(total, range) => `总共${total}条`"
        show-less-items
        :page-size-options="['10', '20', '50', '100']"
        :defaultPageSize="100"
        @change="handleCurrentChange"
        @showSizeChange="handleSizeChange"
      />
    </a-row>
  </div>
</template>

<script>
import 'moment/locale/zh-cn'
import moment from 'moment'
import { v4 as uuidv4 } from 'uuid'
import { columns, innerColumns } from './AdvertisingData'
import { exportExcel } from '../../lib/exportExcel'
import { getSlotData, getSlotDataDay } from '@/api/MeidaMan/api'
export default {
  name: 'advertisingData',
  data() {
    return {
      uuidv4,
      columns,
      data: [],
      innerData: [],
      innerIsLoading: false,
      innerColumns,
      isLoading: false,
      form: this.$form.createForm(this, { name: 'advertisingData' }),
      pageNo: 1,
      pageSize: 100,
      key: '',
      total: 0,
      startTime: moment(moment().format('YYYY-MM-DD')),
      endTime: moment(moment().format('YYYY-MM-DD')).add(1, 'days'),
    }
  },
  mounted() {
    const routeObj = this.$route.query
    if (Object.keys(routeObj).length !== 0) {
      const { slotKey, slotName, slotType } = routeObj
      let slotTypes = Number(slotType)
      this.key = slotKey
      this.loadCall()
    } else {
      this.loadCall()
    }
  },
  methods: {
    handleDetail() {
      this.$router.push({
        path: `data-detail?id=${1}`,
      })
    },
    /**
     * @func 展开时调用
     */
    expand(_, record) {
      const { slotKey: key } = record
      const startTime = moment(moment(this.startTime).format('YYYY-MM-DD')).valueOf()
      const endTime = moment(moment(this.endTime).format('YYYY-MM-DD')).valueOf()
      this.slotDataDay({ key, startTime, endTime })
    },
    /**
     * @func 嵌套列表数据
     */
    async slotDataDay(param) {
      this.innerIsLoading = true
      const [err, innerData] = await getSlotDataDay({ ...param })
      if (!err) {
        this.innerIsLoading = false
        innerData.map((item) => {
          item.computeTime = moment(item.computeTime).format('YYYY-MM-DD')
        })
        if (innerData.length) {
          const adId = innerData[0].slotKey
          const i = this.data.findIndex((item) => {
            return item.slotKey === adId
          })
          this.data = [...this.data.slice(0, i), { ...this.data[i], innerData: innerData }, ...this.data.slice(i + 1)]
        }
      } else {
        this.innerIsLoading = false
        this.$msgErr(err)
      }
    },
    /**
     * @func 页面刚加载就调用
     */
    loadCall() {
      const { name, advertisingType: advertType } = this.form.getFieldsValue()
      this.slotData({
        pageNo: this.pageNo,
        pageSize: this.pageSize,
        name,
        advertType,
        key: this.key,
      })
    },
    /**
     * @func 列表数据
     */
    async slotData(param) {
      this.isLoading = true
      try {
        const {
          detailsData: { count, list },
          totalData: {
            totalActivityShowPv,
            totalActivityShowUv,
            totalActivityJoinPv,
            totalAdvertShowPv,
            totalAdvertValidClick,
            totalExpectIncome,
          },
        } = await getSlotData({ ...param })
        if (list) {
          console.log(totalActivityShowPv)
          const obj = {
            slotName: '总数据',
            activityShowPv: totalActivityShowPv,
            activityShowUv: totalActivityShowUv,
            activityJoinPv: totalActivityJoinPv,
            advertShowPv: totalAdvertShowPv,
            advertValidClick: totalAdvertValidClick,
            expectIncome: totalExpectIncome,
            slotId: 9999,
            slotKey: 'all',
          }
          if (this.pageNo == 1) {
            this.data = [obj, ...list] ?? []
          } else {
            this.data = list ?? []
          }
          this.total = count
          if (this.key !== '') {
            this.total = 1
          }
          this.isLoading = false
        }
      } catch (err) {
        this.isLoading = false
        this.$msgErr(err.message)
      }
    },
    moment,
    /**
     * @func 查询数据
     */
    handleQuery(e) {
      e.preventDefault()
      this.form.validateFields((err, fieldsValue) => {
        if (!err) {
          const startTime = moment(this.startTime).valueOf()
          const endTime = moment(this.endTime).valueOf()
          this.slotData({
            pageNo: 1,
            pageSize: 100,
            name: fieldsValue.name,
            advertType: fieldsValue.advertisingType,
            startTime,
            endTime,
            key: this.key,
          })
        }
      })
    },
    /**
     * 重置表单
     */
    resetForm() {
      this.form.resetFields()
      this.startTime = moment(moment().format('YYYY-MM-DD'))
      this.endTime = moment(moment().format('YYYY-MM-DD')).add(1, 'days')
      this.loadCall()
    },
    /**
     * 导出表格
     */
    handleExportTable() {
      exportExcel(this, columns, 'actions', this.data, '广告位数据')
    },
    /**
     *  @func 改变页面值
     */
    handleCurrentChange(page, pageSize) {
      this.pageNo = page
      this.pageSize = pageSize
      this.loadCall()
    },
    /**
     *  @func 改变页面数据多少
     */
    handleSizeChange(current, size) {
      this.pageNo = current
      this.pageSize = size
      this.loadCall()
    },
  },
}
</script>
<style lang="scss" scoped>
.my-table {
  margin-top: 20px;
}
.right {
  display: flex;
  flex-direction: row-reverse;
  padding-right: 20px;
}
.rights {
  display: flex;
  flex-direction: row-reverse;
}
::v-deep .pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>
